package com.shy.springframework.beans.factory.support;

import com.shy.springframework.beans.BeansException;
import com.shy.springframework.beans.factory.BeanFactory;
import com.shy.springframework.beans.factory.FactoryBean;
import com.shy.springframework.beans.factory.config.BeanDefinition;
import com.shy.springframework.beans.factory.config.BeanPostProcessor;
import com.shy.springframework.beans.factory.config.ConfigurableBeanFactory;
import com.shy.springframework.util.ClassUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yzpang
 * @desc: 抽象BeanFactory, 实现了bean的获取与注册
 * @date: 2023/2/7 14:28
 */
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    private ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();
    @Override
    public Object getBean(String name) {
       return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requireType) throws BeansException {
        return (T) getBean(name);
    }

    protected <T> T doGetBean(String name, Object[] args){
        // 1.判断是否已有单例实例
        Object sharedInstance = getSingleton(name);
        if (sharedInstance != null){
            return (T) getObjectForBeanInstance(sharedInstance, name);
        }
        // 2.构建bean
        BeanDefinition beanDefinition = getBeanDefinition(name);
        Object bean =  (T) createBean(name, beanDefinition, args);
        return (T) getObjectForBeanInstance(bean, name);
    }

    private Object getObjectForBeanInstance(Object beanInstance, String beanName){
        // 非FactoryBean类型
        if (!(beanInstance instanceof FactoryBean)){
            return beanInstance;
        }
        // 从缓存中获取
        Object object = getCachedObjectForFactoryBean(beanName);
        // 使用自定义方法构建bean实例
        if (object == null){
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }
        return object;
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        beanPostProcessors.remove(beanPostProcessor);
        beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return beanPostProcessors;
    }

    public ClassLoader getClassLoader() {
        return classLoader;
    }
}
